package com.eling.elcms.richtexteditor.ueditor.controller;

import com.eling.elcms.core.service.RemotePriorityPropertyPlaceholderConfigurer;
import com.eling.elcms.core.service.ServiceLocator;
import com.eling.elcms.fm.service.IFileStorage;
import com.eling.elcms.fm.service.impl.OssFileStorageImpl;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

@WebServlet(name = "UEditorFilesController", urlPatterns = {"/richeditor/richtexteditor/editor/*"})
public class UEditorFilesController extends HttpServlet {
	private static final Logger log = LoggerFactory.getLogger(UEditorFilesController.class);
	private static final long serialVersionUID = 1L;
    private static final String uriStr = "/richeditor/richtexteditor/editor/";
    private static final String configStr = "/WEB-INF/config";  //配置文件路径
    private static final String fileProperties = File.separator + "file.properties";
    private String rootPath;
    
    public IFileStorage fileStorage = null;
    
    public UEditorFilesController() {
        super();

		fileStorage = ServiceLocator.getService(IFileStorage.class);
    }

    /**
     * 实现文件流返回
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    	
    	try{
    		request.setCharacterEncoding( "utf-8" );
        	
    		response.setHeader("content-type", "application/octet-stream");
    		String requestURI = request.getRequestURI();


			String fileBasedir = RemotePriorityPropertyPlaceholderConfigurer.getPropertyValue("file.basedir");
			String ueditorBasedir = RemotePriorityPropertyPlaceholderConfigurer.getPropertyValue("ueditor.basedir");

			rootPath = fileBasedir.substring(1) + ueditorBasedir;
    		
    		//截取文件路径
    		String filePath = requestURI.substring(requestURI.indexOf(uriStr)+uriStr.length());
            
            InputStream is = fileStorage.read(rootPath +"/"+ filePath);
            response.reset();
            
            OutputStream os = response.getOutputStream();
            
            IOUtils.copy(is, os);  
            
            os.flush();
            os.close();
            is.close();
    	}catch(Exception e){
    		log.error(e.getMessage(), e);
    	}
	}
    
    
    

	/**
	 * 调用doGet方法
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
